package com.xbongbong.pro.service.market.statistics.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.StaticForMarketActivityEntity;
import com.xbongbong.saas.domain.entity.StaticForMarketUpdateEntity;
import com.xbongbong.saas.domain.entity.StaticForUpdateDTO;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.MarketActivityForStaticModel;
import com.xbongbong.saas.model.MarketActivityModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @Auther: yingjianfeng
 * @Date: 2022/3/15 14:42
 * @Description:
 */
@Slf4j
@Service("clue4StaticHandleImpl")
public class Clue4StaticHandleImpl extends AbstractMarketActivity4StaticHandle {
    @Resource
    private MarketActivityForStaticModel marketActivityForStaticModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private EsHelper esHelper;

    @Override
    public Integer type() {
        return XbbRefTypeEnum.CLUE.getCode();
    }

    @Override
    @Async("staticsMarketData")
    public void add(PaasFormDataEntity paasFormDataEntity) throws XbbException {
        try {
            Long id = paasFormDataEntity.getId();
            String corpid = paasFormDataEntity.getCorpid();
            JSONObject data = paasFormDataEntity.getData();
            StaticForMarketActivityEntity addEntity = new StaticForMarketActivityEntity();
            addEntity.setCorpid(corpid);
            StaticForMarketActivityEntity updateEntity = new StaticForMarketActivityEntity();
            updateEntity.setCorpid(corpid);
            List<StaticForMarketActivityEntity> addEntitys = new ArrayList<>();
            List<StaticForMarketActivityEntity> updateEntitys = new ArrayList<>();
            List<Long> delIds = new ArrayList<>();
            // 取一遍关联市场活动的值
            Long marketId = data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr());
            // 市场活动与线索不是强关联  所以这儿只要关联了市场活动才会生成新的记录
            if (Objects.nonNull(marketId)) {
                StaticForMarketActivityEntity marketActivityEntity = marketActivityForStaticModel.getByMarketId(marketId, corpid);
                // 之前中间表存在了市场活动的数据
                if (Objects.nonNull(marketActivityEntity)) {
                    // 市场活动未关联线索，说明该市场活动下一条线索都没有  则需要更新该跳记录的剩余字段
                    if (Objects.isNull(marketActivityEntity.getClueId())) {
                        BeanUtil.copyProperties(marketActivityEntity, updateEntity);
                        updateEntity.setClueId(paasFormDataEntity.getDataId());
                        updateEntity.setClueStage(data.getString(ClueEnum.CLUE_STAGE.getAttr()));
                        updateEntity.setClueStatus(data.getString(ClueEnum.CLUE_STATUS.getAttr()));
                        updateEntity.setClueAddTime(paasFormDataEntity.getAddTime());
                        updateEntity.setCustomerId(null);
                        updateEntity.setSaleStage(null);
                        updateEntity.setSaleOpportunityId(null);
                        updateEntity.setSaleMoney(null);
                        updateEntity.setContractId(null);
                        updateEntity.setContractMoney(null);
                        updateEntitys.add(updateEntity);
                    } else {
                        // 如果该条市场活动关联了市场活动 说明已经产生过线索 现在需要裂变
                        BeanUtil.copyProperties(marketActivityEntity, addEntity);
                        addEntity.setId(null);
                        addEntity.setClueId(paasFormDataEntity.getDataId());
                        addEntity.setClueStage(data.getString(ClueEnum.CLUE_STAGE.getAttr()));
                        addEntity.setClueStatus(data.getString(ClueEnum.CLUE_STATUS.getAttr()));
                        addEntity.setClueAddTime(paasFormDataEntity.getAddTime());
                        addEntity.setCustomerId(null);
                        addEntity.setSaleStage(null);
                        addEntity.setSaleOpportunityId(null);
                        addEntity.setSaleMoney(null);
                        addEntity.setContractId(null);
                        addEntity.setContractMoney(null);
                        addEntitys.add(addEntity);
                    }
                } else {
                    // 这里是处理下异常情况 因为marketId不为空 市场活动是一定存在的 这里重新插入了一下市场活动字段值
                    // 获取失败,之前的市场活动没有添加进去
                    MarketActivityEntityExt byKey = marketActivityModel.getByKey(marketId, corpid);
                    JSONObject marketData = byKey.getData();
                    addEntity.setMarketId(byKey.getId());
                    addEntity.setMarketType(marketData.getString(MarketActivityEnum.GENRE.getAttr()));
                    addEntity.setMarketEndTime(marketData.getLong(MarketActivityEnum.END_TIME.getAttr()));
                    addEntity.setMarketName(marketData.getString(MarketActivityEnum.NAME.getAttr()));
                    addEntity.setActualCost(marketData.getDouble(MarketActivityEnum.REAL_COST.getAttr()));
                    addEntity.setClueId(paasFormDataEntity.getDataId());
                    addEntity.setClueStage(data.getString(ClueEnum.CLUE_STAGE.getAttr()));
                    addEntity.setClueStatus(data.getString(ClueEnum.CLUE_STATUS.getAttr()));
                    addEntity.setClueAddTime(paasFormDataEntity.getAddTime());
                    addEntity.setCustomerId(null);
                    addEntity.setSaleStage(null);
                    addEntity.setSaleOpportunityId(null);
                    addEntity.setSaleMoney(null);
                    addEntitys.add(addEntity);
                }
            }
            // 插入新数据
            if (CollectionsUtil.isNotEmpty(addEntitys)) {
                marketActivityForStaticModel.insertBatch(addEntitys, corpid);
            }
            if (CollectionsUtil.isNotEmpty(updateEntitys)) {
                marketActivityForStaticModel.updateBatchForStatic(updateEntitys);
            }
        } catch (XbbException e) {
            log.error("com.xbongbong.pro.service.marketActivity4Static.MarketActivity4StaticHandle.add ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    @Async("staticsMarketData")
    public void update(PaasFormDataEntity paasFormDataEntity) throws XbbException {
        try {
            String corpid = paasFormDataEntity.getCorpid();
            JSONObject data = paasFormDataEntity.getData();
            Boolean flag = false;
            List<StaticForMarketUpdateEntity> listEntitys = new ArrayList<>();
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_STATICS_MARKET_DATA;
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            boolQueryBuilder.filter(termQuery("clueId", paasFormDataEntity.getDataId()));
            flag = updateClue4MarketActivity(corpid, data, flag, indexTypeEnum, listEntitys, boolQueryBuilder, paasFormDataEntity.getDataId());
            if (flag && CollectionsUtil.isNotEmpty(listEntitys)) {
                // todo 可能需要改动, listEntitys可能数量有点多
                marketActivityForStaticModel.updateBatch(listEntitys, corpid);
            }
        } catch (XbbException e) {
            log.error("com.xbongbong.pro.service.marketActivity4Static.MarketActivity4StaticHandle.update ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    @Async("staticsMarketData")
    public void updateBatch(List<StaticForUpdateDTO> list, String corpid) throws XbbException {
        try {
            String key = null;
            JSONObject data = new JSONObject();
            List<Long> udpateIds = new ArrayList<>();
            Object value = null;
            if (list.size() > 0) {
                key = list.get(0).getData().getString("key");
                data = list.get(0).getData();
                Set<String> strings = data.keySet();
                for (String string : strings) {
                    key = string;
                }
                value = data.get(key);
                list.forEach(item -> {
                    udpateIds.add(item.getId());
                });
            }
            List<StaticForMarketUpdateEntity> listEntitys = new ArrayList<>();
            Boolean flag = false;
            List<String> attrs = new ArrayList<>();
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_STATICS_MARKET_DATA;
            BoolQueryBuilder boolQueryBuilder = getBaseBoolQueryBuilder(corpid, indexTypeEnum);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
            attrs = Arrays.asList(ClueEnum.CLUE_STATUS.getAttr(), ClueEnum.CLUE_STAGE.getAttr());
            if (attrs.contains(key)) {
                boolQueryBuilder.filter(termsQuery("clueId", udpateIds));
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
                for (int i = 0; i <= count / 100; i++) {
                    PageRequest pageRequest = EsUtil.setPage(sourceBuilder, i + 1, 100);
                    XbbAggregatedPage<StaticForMarketActivityEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, StaticForMarketActivityEntity.class);
                    List<StaticForMarketActivityEntity> content = esEntities.getContent();
                    String finalKey = key;
                    Object finalValue = value;
                    for (StaticForMarketActivityEntity item : content) {
                        StaticForMarketUpdateEntity staticForMarketUpdateEntity = new StaticForMarketUpdateEntity();
                        BeanUtil.copyProperties(item, staticForMarketUpdateEntity);
                        staticForMarketUpdateEntity.setCorpid(corpid);
                        staticForMarketUpdateEntity.setId(item.getDataId());

                        if (Objects.equals(finalKey, ClueEnum.CLUE_STATUS.getAttr())) {
                            flag = true;
                            staticForMarketUpdateEntity.setClueStatus(finalValue.toString());
                        }
                        if (Objects.equals(finalKey, ClueEnum.CLUE_STAGE.getAttr())) {
                            flag = true;
                            staticForMarketUpdateEntity.setClueStage(finalValue.toString());
                        }
                        listEntitys.add(staticForMarketUpdateEntity);
                    }
                }
            }
            if (flag && CollectionsUtil.isNotEmpty(listEntitys)) {
                // 可能需要改动, listEntitys可能数量有点多
                marketActivityForStaticModel.updateBatch(listEntitys, corpid);
            }
        } catch (XbbException e) {
            log.error("com.xbongbong.pro.service.marketActivity4Static.MarketActivity4StaticHandle.updateBatch ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    @Async("staticsMarketData")
    public void deleteBatch(List<Long> idIn, String corpid, Integer del) throws XbbException {
        try {

            if (idIn.size() == 0) {
                return;
            }
            // 这个优先级最高,必须得最先处理
            List<Long> otherNeedDel = new ArrayList<>();
            List<Long> delIds = new ArrayList<>();

            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_STATICS_MARKET_DATA;
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            // 这里暂不处理这个del条件
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
            List<StaticForMarketActivityEntity> staticList = new ArrayList<>();
            long count;
            // if 是正常删除 和 彻底删除   else是恢复
            if (!Objects.equals(del, DelEnum.NORMAL.getDel())) {
                // 是否是正常删除
                if (Objects.equals(del, DelEnum.DELETE.getDel())) {
                    boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                }
                // 是否是彻底删除
                if (Objects.equals(del, DelEnum.REMOVE_COMPLETELY.getDel())) {
                    boolQueryBuilder.filter(termQuery("del", DelEnum.DELETE.getDel()));
                }
                // 获取要删除的线索对应的marketId一份, 已备后续恢复
                Map<Long, StaticForMarketActivityEntity> entityMap = getMarketEntity(idIn, "clueId", corpid);
                boolQueryBuilder.filter(termsQuery("clueId", idIn));
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                count = xbbElasticsearchRestTemplate.count(searchRequest, StaticForMarketActivityEntity.class);
                //每个市场活动下的图表数据的id集合
                Map<Long, Set<Long>> marketIdAndSet = new HashMap<Long, Set<Long>>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                if (count > 0) {
                    getDelIds(delIds, sourceBuilder, searchRequest, count, marketIdAndSet);
                } else {
                    return;
                }
                // 判断是否需要新建一个对应的staticMarketEntity
                // fix: 2022/3/23 批量删会有问题
//                List<Long> flag2AddNewData = getFlag2AddNewData(entityMap.keySet(), count, "marketId", corpid, "marketId");
                List<Long> flag2AddNewData = getAddNewData(corpid, entityMap, marketIdAndSet);

                if (flag2AddNewData.size() > 0) {
                    for (Long marketId : flag2AddNewData) {
                        StaticForMarketActivityEntity staticForMarketActivityEntity1 = entityMap.get(marketId);
                        staticForMarketActivityEntity1.setDataId(null);
                        staticForMarketActivityEntity1.setId(null);
                        staticForMarketActivityEntity1.setClueId(null);
                        staticForMarketActivityEntity1.setClueAddTime(null);
                        staticForMarketActivityEntity1.setClueStage(null);
                        staticForMarketActivityEntity1.setClueStatus(null);
                        staticForMarketActivityEntity1.setCustomerId(null);
                        staticForMarketActivityEntity1.setSaleStage(null);
                        staticForMarketActivityEntity1.setSaleOpportunityId(null);
                        staticForMarketActivityEntity1.setSaleMoney(null);
                        staticList.add(staticForMarketActivityEntity1);
                    }
                }
            } else {
                boolQueryBuilder.filter(termsQuery("clueId", idIn));
                boolQueryBuilder.filter(termQuery("del", DelEnum.DELETE.getDel()));
                // 获取所要的销售线索关联的所有marketId
                Set<Long> tagetIds = getTagetIds(idIn, corpid, IndexTypeEnum.IDX_STATICS_MARKET_DATA, "clueId");
                // 获取还原该线索需要删除的dataId
                otherNeedDel = getNeedToDeleteId(tagetIds, corpid, "marketId");
                boolQueryBuilder.filter(termsQuery("clueId", idIn));
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                getDelIds(delIds, sourceBuilder, searchRequest, idIn.size());

            }

            if (otherNeedDel.size() > 0) {
                marketActivityForStaticModel.deleteBatch(otherNeedDel, corpid, DelEnum.DELETE.getDel());
            }
            if (delIds.size() > 0) {
                // 可能需要改动, listEntitys可能数量有点多
                marketActivityForStaticModel.deleteBatch(delIds, corpid, del);
            }
            if (staticList.size() > 0) {
                marketActivityForStaticModel.insertBatch(staticList, corpid);
            }

        } catch (XbbException e) {
            log.error("com.xbongbong.pro.service.marketActivity4Static.MarketActivity4StaticHandle.deleteBatch ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 更新线索时是否需要处理中间表
     * date: 2022/3/14 9:44 上午
     * @author yingjf
     */
    private Boolean updateClue4MarketActivity(String corpid, JSONObject data, Boolean flag, IndexTypeEnum indexTypeEnum, List<StaticForMarketUpdateEntity> listEntitys, BoolQueryBuilder boolQueryBuilder, Long clueId) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        searchRequest.source(sourceBuilder);
        long count = xbbElasticsearchRestTemplate.count(searchRequest, StaticForMarketActivityEntity.class);
        if (Objects.nonNull(data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr())) && count == 0L) {
            // 这儿得重新走一遍流程 修改之前没有关联市场活动的线索关联了市场活动
            dealAddMarketId(corpid, data, clueId);
            return false;
        }
        if (Objects.isNull(data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr()))) {
            List<Long> delIds = new ArrayList<>();
            for (int i = 0; i <= count / 100; i++) {
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, i + 1, 100);
                XbbAggregatedPage<StaticForMarketActivityEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, StaticForMarketActivityEntity.class);
                List<StaticForMarketActivityEntity> content = esEntities.getContent();
                for (StaticForMarketActivityEntity entity : content) {
                    delIds.add(entity.getDataId());
                }
            }
            if (delIds.size() > 0) {
                marketActivityForStaticModel.deleteBatch(delIds, corpid, DelEnum.DELETE.getDel());
            }
            return false;
        }
        // 如果关联市场活动改变了之后
        Long marketId = data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr());
        MarketActivityEntityExt byKey = marketActivityModel.getByKey(marketId, corpid);
        JSONObject marketData = byKey.getData();
        for (int i = 0; i <= count / 100; i++) {
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, i + 1, 100);
            XbbAggregatedPage<StaticForMarketActivityEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, StaticForMarketActivityEntity.class);
            List<StaticForMarketActivityEntity> content = esEntities.getContent();
            for (StaticForMarketActivityEntity entity : content) {
                if (Objects.isNull(data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr()))) {
                    entity.setDel(DelEnum.DELETE.getDel());
                }

                StaticForMarketUpdateEntity staticForMarketUpdateEntity = new StaticForMarketUpdateEntity();
                staticForMarketUpdateEntity.setCorpid(corpid);
                if (!Objects.equals(entity.getMarketId(), marketId)) {
                    staticForMarketUpdateEntity.setMarketId(byKey.getId());
                    staticForMarketUpdateEntity.setMarketType(marketData.getString(MarketActivityEnum.GENRE.getAttr()));
                    staticForMarketUpdateEntity.setMarketEndTime(marketData.getLong(MarketActivityEnum.END_TIME.getAttr()));
                    staticForMarketUpdateEntity.setMarketName(marketData.getString(MarketActivityEnum.NAME.getAttr()));
                    staticForMarketUpdateEntity.setActualCost(marketData.getDouble(MarketActivityEnum.REAL_COST.getAttr()));
                    flag = true;
                }
                if (StringUtil.isNotEmpty(data.getString(ClueEnum.CLUE_STATUS.getAttr())) && !Objects.equals(entity.getClueStatus(), data.getString(ClueEnum.CLUE_STATUS.getAttr()))) {
                    flag = true;
                    staticForMarketUpdateEntity.setClueStatus(data.getString(ClueEnum.CLUE_STATUS.getAttr()));
                }
                if (StringUtil.isNotEmpty(data.getString(ClueEnum.CLUE_STAGE.getAttr())) && !Objects.equals(entity.getClueStage(), data.getString(ClueEnum.CLUE_STAGE.getAttr()))) {
                    flag = true;
                    staticForMarketUpdateEntity.setClueStage(data.getString(ClueEnum.CLUE_STAGE.getAttr()));
                }
                if (flag) {
                    staticForMarketUpdateEntity.setId(entity.getDataId());
                    listEntitys.add(staticForMarketUpdateEntity);
                }
            }
        }
        return flag;
    }

    private void dealAddMarketId(String corpid, JSONObject data, Long clueId) throws XbbException {
        List<Long> delIds = new ArrayList<>();
        StaticForMarketActivityEntity staticForMarketActivityEntity = new StaticForMarketActivityEntity();
        StaticForMarketActivityEntity staticForMarketActivityEntity3 = marketActivityForStaticModel.getByMarketId(data.getLong(ClueEnum.MARKET_ACTIVITY_ID.getAttr()), corpid);
        if(staticForMarketActivityEntity3==null){
            return;
        }
        if (Objects.isNull(staticForMarketActivityEntity3.getClueId())) {
            // 删除只会出现在第一此添加市场活动下的线索时
            delIds.add(staticForMarketActivityEntity3.getId());
        }
        staticForMarketActivityEntity3.setCustomerId(null);
        staticForMarketActivityEntity3.setSaleMoney(null);
        staticForMarketActivityEntity3.setSaleStage(null);
        staticForMarketActivityEntity3.setSaleOpportunityId(null);
        BeanUtil.copyProperties(staticForMarketActivityEntity3, staticForMarketActivityEntity);
        staticForMarketActivityEntity.setId(null);
        staticForMarketActivityEntity.setCorpid(corpid);
        // 销售线索
        staticForMarketActivityEntity.setClueStatus(data.getString(ClueEnum.CLUE_STATUS.getAttr()));
        staticForMarketActivityEntity.setClueStage(data.getString(ClueEnum.CLUE_STAGE.getAttr()));
        staticForMarketActivityEntity.setClueId(clueId);
        // 查询市场活动转化的客户
        List<PaasFormDataEntityExt> clue2Customer = getClue2Customer(corpid, Arrays.asList(clueId));
        List<Long> customerIds = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(clue2Customer)) {
            clue2Customer.forEach(item -> customerIds.add(item.getDataId()));
        }
        List<StaticForMarketActivityEntity> entities = new ArrayList<>();
        if (customerIds.size() > 0) {
            staticForMarketActivityEntity.setCustomerId(customerIds.get(0));
            // 查询销售机会关联的客户
            List<PaasFormDataEntityExt> opportuniry2Customer = getOpportuniry2Customer(corpid, customerIds);
            if (opportuniry2Customer.size() > 0) {
                for (PaasFormDataEntityExt paasFormDataEntityExt : opportuniry2Customer) {
                    JSONObject data1 = paasFormDataEntityExt.getData();
                    StaticForMarketActivityEntity staticForMarketActivityEntity1 = new StaticForMarketActivityEntity();
                    BeanUtil.copyProperties(staticForMarketActivityEntity, staticForMarketActivityEntity1);

                    // 销售机会
                    staticForMarketActivityEntity1.setSaleMoney(data1.getDoubleValue(SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr()));
                    staticForMarketActivityEntity1.setSaleStage(data1.getString(SalesOpportunityEnum.SALE_STAGE.getAttr()));
                    staticForMarketActivityEntity1.setSaleOpportunityId(paasFormDataEntityExt.getDataId());
                    entities.add(staticForMarketActivityEntity1);
                }
            } else {
                entities.add(staticForMarketActivityEntity);
            }
        } else {
            entities.add(staticForMarketActivityEntity);
        }
        if (entities.size() > 0) {
            marketActivityForStaticModel.insertBatch(entities, corpid);
        }
        if (delIds.size() > 0) {
            marketActivityForStaticModel.deleteBatch(delIds, corpid, DelEnum.DELETE.getDel());
        }
    }

    private List<PaasFormDataEntityExt> getClue2Customer(String corpid, List<Long> clueIds) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String esAttr4Keyword = CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.CLUE_ID);
        boolQueryBuilder.filter(termsQuery(esAttr4Keyword, clueIds));
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.DATA_ID);
        fieldList.add("data." + CustomerManagementEnum.CLUE_ID.getAttr());
        return esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CUSTOMER, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
    }

    public List<PaasFormDataEntityExt> getOpportuniry2Customer(String corpid, Collection<Long> customerIds) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String esAttr4Keyword = SalesOpportunityEnum.getEsAttr4Keyword(SalesOpportunityEnum.CUSTOMER_NAME);
        boolQueryBuilder.filter(termsQuery(esAttr4Keyword, customerIds));
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        return esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OPPORTUNITY, boolQueryBuilder, PaasFormDataEntityExt.class, null);
    }

}
